package com.bsy.network.interceptor

import android.text.TextUtils
import com.bsy.network.constant.baseUrlMap
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * Created by Sincerity on 2023/5/30.
 * Copyright
 * 描述：
 */
class BaseUrlInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val builder: Request.Builder = request.newBuilder()
        //拦截retrofit注解的header配置信息
        val list: List<String> = request.headers("baseUrl")
        if (list.isNotEmpty()) {
            //移除掉header 因为服务器不需要这个header,这个header只是在拦截器里用到
            builder.removeHeader("baseUrl")
            val key = list[0]
            //如果配置的header信息在HashMap里有声明
            if (!TextUtils.isEmpty(key) && baseUrlMap.containsKey(key)) {
                val url: String? = baseUrlMap[key]
                val newBaseUrl = if (url.isNullOrEmpty()) request.url else url.toHttpUrl()
                val oldBaseUrl: HttpUrl = request.url
                //将旧的请求地址里的协议、域名、端口号替换成配置的请求地址
                val newFullUrl =
                    oldBaseUrl.newBuilder().scheme(newBaseUrl.scheme).host(newBaseUrl.host).port(newBaseUrl.port)
                        .build()

                //创建带有新地址的新请求
                val newRequest: Request = builder.url(newFullUrl).build()
                return chain.proceed(newRequest)
            }
        }
        return chain.proceed(request)
    }
}